"""
使用aiohttp请求代理服务器
请求http和https网页均适用
"""
import asyncio
import aiohttp
import requests

# 应用账号（请替换为真实账号）
app_key = 'app_key'
# 应用密码（请替换为真实密码）
app_secret = 'app_secret'
# 用户名密码认证
proxy_auth = aiohttp.BasicAuth(app_key, app_secret)

api_url = "https://api.xiaoxiangdaili.com/ip/get"

# 要访问的目标网页
target_url = "http://httpbin.org/ip"

url = api_url + "?appKey=" + app_key + "&appSecret=" + app_secret + "&cnt=1&wt=text"

# API接口返回的proxy_list
proxy_list = requests.get(url).text
print("API response: " + proxy_list)


async def fetch(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, proxy="http://" + proxy_list, proxy_auth=proxy_auth) as resp:
            content = await resp.read()
            print(f"status_code: {resp.status}, content: {content}")



loop = asyncio.get_event_loop()
# 异步发出n次请求
tasks = [fetch(target_url) for _ in range(2)]
loop.run_until_complete(asyncio.wait(tasks))